/**
 * Express web框架的应用模块
 * 1.导入所需模块
 * 2.导入路由模块
 * 3.应用层中间件
 * 4.定义路由
 * 5.导出Express应用实例
 */
// 1. 导入所需的模块
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 新增：导入MySQL相关模块
const session = require("express-session");
const MySQLStore = require('express-mysql-session')(session); // 替换SQLiteStore
const config = require("./common/config");

//导入Swagger-ui-express模块、
const swaggerUi = require('swagger-ui-express');
//导入Swagger-jsdoc模块
const swaggerJsdoc = require('swagger-jsdoc');
//导入初始化数据库中间件
const initMysqlDB = require("./controller/init");

//2.导入路由模块
//导入默认路由
var indexRouter = require('./routes/index');
//导入用户路由
var usersRouter = require('./routes/users');
//导入物品路由
var itemRouter = require('./routes/items');
//导入地址路由
var addressRouter = require('./routes/address');
//导入仓库路由
var warehouseRouter = require('./routes/warehouse');
//导入预约路由
var reservationRouter = require('./routes/reservation');
//导入评论路由
var reviewRouter = require('./routes/review');
//导入仓库分区路由
var warehouseZoneRouter = require('./routes/warehousezone');
//导入货架路由
var shelvesRouter = require('./routes/shelves');
//导入货架物品路由
var shelfItemRouter = require('./routes/shelfItem');

// 3. 应用层中间件
var app = express();

// JSON解析
app.use(logger('dev'));
app.use(express.json());
// URL编码解析
app.use(express.urlencoded({ extended: false }));
// Cookie
app.use(cookieParser());
// 静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 中间件：Swagger
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '校园物品托管仓库管理接口',
      version: '1.0.0'
    },
  },
  apis: [path.join(__dirname, './routes/*.js')],
};
  
const openapiSpecification = swaggerJsdoc(options);
app.use('/dev-api', swaggerUi.serve, swaggerUi.setup(openapiSpecification));

// 中间件：数据库初始化           

const MysqlDB = require('./model/db/init');    
  
// 应用启动时初始化数据库连接池  
const mysqlDB = new MysqlDB();  
app.set('mysqlDB', mysqlDB); // 将mysqlDB实例存储在app对象上  
app.use(async (req, res, next) => {
  if (mysqlDB.pool) {
    next();
  } else {
    await mysqlDB.createTables();
    next();
  }
});
// app.use(initMysqlDB()); // 调用MysqlDB的initDB方法
// app.use(mysqlDB);

// 修改Session存储为MySQL
const mysqlSessionStore = new MySQLStore({
    host: config.dbConfig.host,
    user: config.dbConfig.user,
    password: config.dbConfig.password,
    database: config.dbConfig.database,
  clearExpired: true, // 自动清理过期会话（可选）
});

app.use(session({
  secret: "sdhfj@#dfh@3",
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 },
  store: mysqlSessionStore,
}));

//错误处理
app.use((err, req, res, next) => {  
  console.error('未捕获的错误:', err);  
  res.status(500).json({ error: '服务器内部错误' });  
});

//4.定义路由
//默认路由 -> /
app.use('/', indexRouter);
//用户路由 -> /users
app.use('/users', usersRouter);
app.use('/items', itemRouter);
app.use('/address', addressRouter);
app.use('/warehouse', warehouseRouter);
app.use('/reservation', reservationRouter);
app.use('/review', reviewRouter);
app.use('/warehousezone', warehouseZoneRouter);
app.use('/shelves', shelvesRouter);
app.use('/shelfItem', shelfItemRouter);

// 5. 导出Express应用实例
module.exports = app;